using System;
using System.Collections.Generic;
using System.Text;

namespace MoXAML.MVVM
{
    public class ValidationViewModelBase<T> : ViewModelBase
    {
        private Dictionary<string, List<Action<T>>> _validation = new Dictionary<string, List<Action<T>>>();
        private List<string> _failures = new List<string>();

        protected string GetErrors(T instance)
        {
            StringBuilder sb = new StringBuilder();
            foreach (var kvp in _validation)
            {
                sb.AppendFormat("{0}{1}", PerformValidation(kvp.Key, instance), Environment.NewLine);
            }
            return sb.ToString();
        }

        protected void AddValidation(string key, Action<T> validation)
        {
            if (!_validation.ContainsKey(key))
            {
                List<Action<T>> value = new List<Action<T>>();
                _validation.Add(key, value);
            }
            _validation[key].Add(validation);
        }

        protected string PerformValidation(string key, T instance)
        {
            if (string.IsNullOrWhiteSpace(key)) throw new ArgumentException("key");

            _failures.Clear();
            if (_validation.ContainsKey(key))
            {
                foreach (var action in _validation[key])
                {
                    action(instance);
                }
            }

            StringBuilder sb = new StringBuilder();
            foreach (string failure in _failures)
            {
                sb.AppendFormat("{0}{1}", failure, Environment.NewLine);
            }
            return sb.ToString();
        }

        protected void AddFailure(string message)
        {
            _failures.Add(message);
        }

    }
}
